<template>
	<div class="wrapper">
		<div class="chat-window">
			<!-- 添加头部 -->
			<div class="header">饿了么客服</div>

			<!-- 添加聊天对话框 -->
			<div class="messages">
				<div v-for="(message, index) in chatHistory" :key="index" class="message">
					<!-- 添加用户头像和昵称 -->
					<div v-if="message.isUser" class="user-info">
						<div class="avatar user-avatar"></div>
						<div class="nickname">User:</div>
					</div>
					<!-- 添加客服头像和昵称 -->
					<div v-else class="bot-info">
						<div class="avatar bot-avatar"></div>
						<div class="nickname">智能客服：</div>
					</div>

					<div class="message-content" :class="{ 'user-message': message.isUser, 'bot-message': !message.isUser }">
						<div class="message-text">{{ message.content }}</div>
						<div class="message-time">{{ getCurrentTime() }}</div> <!-- 显示消息发送时间 -->
					</div>

				</div>
			</div>

			<!-- 添加底部输入框和发送按钮 -->
			<div class="input-container">
				<input v-model="userMessage" type="text" placeholder="输入消息" @keyup.enter="sendMessage">
				<button @click="sendMessage">发送</button>
			</div>

			<!-- 添加悬浮窗 -->
			<!-- <div class="floating-button" @click="turnToHuman">人工客服</div> -->
			<!-- <div class="floating-button" @click="turnToHuman">
				{{ showPhoneNumber ? '123-456-7890' : '人工客服' }}
			</div> -->
			<div class="floating-button" @click="turnToHuman">
				<div v-if="!showPhoneNumber" class="phone-icon">
				<i class="fa fa-phone"></i>
				</div>
				<div v-else class="phone-number">123-456-7890</div>
			</div>
			<!-- 添加自定义的Footer组件 -->
			<Footer></Footer>
		</div>
	</div>
</template>

<script>
	// import {
	// 	ref,
	// 	onMounted
	// } from 'vue';
	// import axios from 'axios';
	import Footer from '../components/FooterPage.vue';

	import CryptoJS from 'crypto-js';

	//import qs from 'qs';

	export default {
		name: 'ConsultationPage',
		components: {
			Footer,
		},
		data() {
			return {
				appId: '6033a1d9',
				status: 'init',
				ttsWS: null,
				totalRes: '',
				userInput: '',
				chatHistory: [],
				userMessage: '',
				showPhoneNumber: false,
			};
		},
		methods: {
			

		
			getCurrentTime() {
				const now = new Date();
				//const year = now.getFullYear().toString();
				const hours = now.getHours().toString().padStart(2, '0');
				const minutes = now.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},

			sendMessage() {
				
				const message = this.userMessage.trim();
				//console.log(message);
				if (message === '') {
					return;
				}

				// 发送用户消息并添加到聊天历史
				this.addUserMessage(message);
				this.start(message);


				// 调用后端接口发送消息并获取回复
				//callBackendAPI(message);
				//console.log("Dsds");
				//console.log(this.totalRes);
				//this.addBotMessage(this.totalRes);


				// 清除输入框
				this.userMessage = '';
			},
			turnToHuman(){
				this.showPhoneNumber = true;
			},

			addUserMessage(content) {
				this.chatHistory.push({
					content,
					isUser: true
				});
			},

			addBotMessage(content) {
				this.chatHistory.push({
					content,
					isUser: false
				});
			},


			getWebsocketUrl() {
				return new Promise((resolve	) => {
					const apiKey = 'dc8c4fd842fca389c26d82f6614c7a94';
					const apiSecret = 'NmVjOTNlMDk1NmJmODI4MTNlN2VmOTBm';
					const url = 'wss://spark-api.xf-yun.com/v1.1/chat';
					const host = window.location.host;
					const date = new Date().toGMTString();
					const algorithm = 'hmac-sha256';
					const headers = 'host date request-line';
					const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`;
					const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
					const signature = CryptoJS.enc.Base64.stringify(signatureSha);
					const authorizationOrigin =
						`api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
					const authorization = window.btoa(authorizationOrigin);
					const finalUrl = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
					console.log(finalUrl)
					resolve(finalUrl);
				});
			},
			setStatus(status) {
				this.status = status;
			},
			connectWebSocket(message) {
				this.setStatus('ttsing');
				let accumulatedContent = '';
				this.getWebsocketUrl().then((url) => {
					let ttsWS;
					if ('WebSocket' in window) {
						ttsWS = new WebSocket(url);
					} else {
						alert('浏览器不支持WebSocket');
						return;
					}
					this.ttsWS = ttsWS;
					ttsWS.onopen = () => {
						this.webSocketSend(message);
					};
					ttsWS.onmessage = (e) => {
						this.totalRes = this.result(e.data).then((content) => {
							accumulatedContent += content;
							//this.addBotMessage(accumulatedContent);
							// ... 其他逻辑
						});
						console.log(accumulatedContent);
					};
					//this.addBotMessage(accumulatedContent);
					ttsWS.onerror = () => {
						clearTimeout(this.playTimeout);
						this.setStatus('error');
						alert('WebSocket报错，请f12查看详情');
						console.error(`详情查看：${encodeURI(url.replace('wss:', 'https:'))}`);
					};
					ttsWS.onclose = (e) => {
						console.log(e);
						this.addBotMessage(accumulatedContent);
					};
				});
			},
			webSocketSend(message) {
				const params = {
					header: {
						app_id: this.appId,
						uid: 'fd3f47e4-d',
					},
					parameter: {
						chat: {
							domain: 'general',
							temperature: 0.5,
							max_tokens: 1024,
						},
					},
					payload: {
						message: {
							text: [{
								"role": "system",
								"content": "你现在扮演外卖平台客服，你彬彬有礼、十分耐心；接下来请用客服的口吻和用户对话。"
							}, {
								"role": "user",
								"content": message,
							}],
						},
					},
				};
				console.log(JSON.stringify(params));
				this.ttsWS.send(JSON.stringify(params));
			},
			start(message) {
				this.totalRes = '';
				this.connectWebSocket(message);
			},
			async result(resultData) {
				let jsonData = JSON.parse(resultData);
				//this.totalRes += resultData;
				const content = jsonData.payload.choices.text[0].content;
				//this.$refs.outputText.value = this.totalRes;
				if (jsonData.header.code !== 0) {
					alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
					console.error(`${jsonData.header.code}:${jsonData.header.message}`);
					return;
				}
				if (jsonData.header.code === 0 && jsonData.header.status === 2) {
					this.ttsWS.close();
					this.setStatus('init');
				}
				return content;
			},
		},
	};
</script>



<style scoped>
	.message-time {
		color: #999;
		font-size: 12px;
		margin-top: 4px;
		margin-left: 16px;
	}

	.wrapper {
		width: 100%;
		height: 100%;
	}

	.chat-window {
		display: flex;
		flex-direction: column;
		height: 100vh;
		padding: 20px;
	}

	.header {
		/* background-color: #2196f3;
		color: #fff;
		padding: 20px;
		text-align: center;
		font-weight: bold;
		border-radius: 10px;
		/* 添加圆角样式 */

		/* font-size: 24px; */
		/* 增加字体大小 */ 
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;

		/* 固定定位 */
		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;

		display: flex;
		justify-content: center;
		align-items: center;
	}

	.messages{
		width: 100%;
		margin-top: 12vw;
	}
	.message {
		/* display: flex; */
		/* width: 100%;
		margin-top: 12vw; */
		margin-top: 2vw;
	}

	.user-info,
	.bot-info {
		display: flex;
		align-items: flex-start;
		margin-top: 4px;
		margin-left: 16px;
		width: 100%;
	}
	.user-info .avatar {
		background-color: #ff4081;
		background-image: url('../assets/userImg/yhtx06.png');
		/* 替换为用户头像图片路径 */
		background-size: cover;
		background-position: center;
	}

	.bot-info .avatar {
		background-color: #3f51b5;
		background-image: url('../assets/userImg/yhtx02.png');
		/* 替换为用户头像图片路径 */
		background-size: cover;
		background-position: center;
	}

	.nickname {
		font-weight: bold;
		margin-right: 4px;
	}

	.message-content {
		background-color: #f5f5f5;
		border-radius: 8px;
		padding: 8px;
		margin-left: 8px;
	}

	.message-text {
		margin-bottom: 4px;
	}

	.user-message {
		display: flex;
		align-items: center;
		background-color: #e4e4e4;
		padding: 8px;
		border-radius: 4px;
	}

	.bot-message {
		display: flex;
		align-items: center;
		background-color: #f0f8ff;
		padding: 8px;
		border-radius: 4px;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 8px;
	}

	.user-avatar {
		background-color: #ff4081;
	}

	.bot-avatar {
		background-color: #3f51b5;
	}

	.nickname {

		font-weight: bold;
		margin-right: 4px;
		margin-top: 10px;
	}

	/* .input-container {
		border-radius: 10px;
		width: 100px;


		position: fixed;
		display: flex;
		gap: 10px;
		bottom: 100px;
		margin-left: 30px;
		font-size: large;

	} */
	.input-container {
		border-radius: 10px;
		width: 80%;
		position: fixed;
		display: flex;
		gap: 10px;
		bottom: 100px;
		margin-left: 30px;
		font-size: large;
		background-color: #f0f0f0;
		padding: 10px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.input-container input {
		flex: 1;
		border: none;
		outline: none;
		padding: 5px;
		font-size: 16px;
		border-radius: 5px;
	}

	.input-container button {
		border: none;
		background-color: #007bff;
		color: #fff;
		padding: 8px 16px;
		border-radius: 5px;
		cursor: pointer;
		font-size: 16px;
		transition: background-color 0.3s;
	}

	.input-container button:hover {
		background-color: #0056b3;
	}


	/* .floating-button {
		position: fixed;
		bottom: 100px;
		right: 20px;
		background-color: #b8b8b8;
		color: #0d0d0d;
		padding: 10px;
		border-radius: 10px;
		cursor: pointer;
		font-size: small;
	} */
	.floating-button {
		position: fixed;
		bottom: 300px;
		right: 20px;
		background-color: #007bff;
		color: #fff;
		padding: 10px;
		border-radius: 15%;
		cursor: pointer;
		font-size: 20px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		transition: background-color 0.3s;
	}

	.floating-button:hover {
		background-color: #0056b3;
	}
</style>
